from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
import json
from chatterbot import ChatBot
from chatgo import settings
from django.views.generic import View
import urllib.parse
import urllib.request
import http.client
import requests
from chatterbot.trainers import ListTrainer
import os

# Create your views here.
def chat(request):
    url = 'http://127.0.0.1:8080/wxoatest/recv_qiyu'
    params = {
        'time': 1900,
        'checksum': "TEXT",
        'eventType': "test"
    }
    data = {
        "uid": "user1",
        "msgType": "TEXT",
        "content": "世界，你好。"
    }
    headers = {"Content-type": "application/json", "Accept": "text/plain"}

    r = requests.post(url, params, json)

    context = {'hello': 'hello world'}
    return render(request, 'hello.html', context)


class ChatBotViewMixin(object):
    charBot = ChatBot(**settings.CHATTERBOT)


class ChatBotView(ChatBotViewMixin, View):
    def get(self, request, *args, **kwargs):
        input_data = request.GET.get('q')
        callback = request.GET.get('callback')
        # chat_session_id = request.session.get('chat_session_id')
        #
        # if chat_session_id:
        #     chat_session = self.charBot.conversation_sessions.get(chat_session_id)
        # else:
        #     chat_session = self.charBot.conversation_sessions.new()
        #     chat_session_id = str(chat_session.uuid)
        #     request.session['chat_session_id'] = chat_session_id

        response_data = self.charBot.get_response(input_data, None)
        return HttpResponse(callback + '(' + json.dumps({
            "answers": [
                {
                    "respond": response_data.text,
                    "suggestions": []
                }
            ],
        }) + ')', content_type='application/json')


def add(request):
    context = {'hello': 'hello world'}
    return render(request, 'index.html', context)


class UEditor(View):
    path = os.getcwd()
    with open(os.path.join(settings.JSON_PATH, 'config.json'), encoding='utf-8') as f:
        cf = json.load(f)

    def get(self, request, *args, **kwargs):
        action = request.GET.get('action')
        callback = request.GET.get('callback')
        if action == 'config':
            result = self.cf
        elif action in ['uploadimage', 'uploadscrawl', 'uploadvideo', 'uploadfile']:
            result = self.upload()
        elif action == 'listimage' or action == 'listfile':
            result = self.list()
        elif action == 'catchimage':
            result = self.crawler()
        else:
            result = json.dump({'state': '请求地址出错'})
        if callback:
            return HttpResponse(callback + '(' + json.dumps(result) + ')', content_type='application/json')
        else:
            return JsonResponse(result, status=200)

    def upload(self):
        return ''

    def list(self):
        return ''

    def crawler(self):
        return ''


class ManageRepo(ChatBotViewMixin, View):
    def get(self, request, *args, **kwargs):
        return render(request, 'manage.html')

    def post(self, request, *args, **kwargs):
        """
            Return a response to the statement in the posted data.
        """
        # input_data = json.loads(request.read().decode('utf-8'))
        q = request.POST.get('questions[]')
        a = request.POST.get('answers[]')
        self.charBot.set_trainer(ListTrainer)
        self.charBot.train([
            q,
            a,
        ])
        return render(request, 'manage.html', status=200)
        # response_data = {'result': 'success'}
        # return JsonResponse(response_data, status=303)
